﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using NNS.Framework;
using NNS.UI;
using QLTB.BusinessLayer;
using QLTB.BusinessObjects;
using QLTB.Common;
using QLTB.LinhKien.Entity;

namespace QLTB.LinhKien.UI
{
    public enum LinhKienType
    {
        CPU = 0,
        MainBoard = 1,
        Monitor = 2,
        Ram = 3,
        HDD = 4,
        CD_DVD = 5,
        Orther = 6
    }

    [System.ComponentModel.ToolboxItem(false)]
    public partial class ucLinhKien : MyUIBase
    {
        #region Column enum

        public enum Column
        {
            None,
            MaTB,
            Lock
        }

        #endregion

        private LinhKienType _style;
        private TBL_THIETBI _thietbi;
        private Column m_Column;

        public ucLinhKien()
        {
            InitializeComponent();
            bm.SetPopupContextMenu(gcList, pm);
            try
            {
                tBL_TinhtrangTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_TinhtrangTableAdapter.Fill(dsTinhTrang.TBL_Tinhtrang);
                tBL_nhasxTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_nhasxTableAdapter.Fill(dsNSX.TBL_nhasx);
                tBL_NHACUNGCAPTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_NHACUNGCAPTableAdapter.Fill(dsNHACUNGCAP.TBL_NHACUNGCAP);
            }
            catch (Exception ex)
            {
                ShowWarning(ex.Message, "Quản lý thiết bị");
            }
            TBL_quyenBL.IgnoreError = true;
            if (!TBL_quyenBL.isTaomoi(EnumComponent.iComponents))
            {
                gbList.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            }
            TBL_quyenBL.IgnoreError = false;
        }

        public LinhKienType Style
        {
            get { return _style; }
            set
            {
                _style = value;
                if (value == LinhKienType.CPU)
                {
                    colDungluong.Visible = false;
                }
                else if (value == LinhKienType.MainBoard)
                {
                    colDungluong.Visible = false;
                    colsocket.Visible = false;
                    coltocdo.Visible = false;
                }
                else if (value == LinhKienType.Monitor)
                {
                    colsocket.Visible = false;
                    coltocdo.Visible = false;
                    colDungluong.Visible = false;
                    colbus.Visible = false;
                }
                else if (value == LinhKienType.Ram)
                {
                    colsocket.Visible = false;
                    coltocdo.Visible = false;
                }
                else if (value == LinhKienType.HDD)
                {
                    colsocket.Visible = false;
                    colbus.Visible = false;
                }
                else if (value == LinhKienType.CD_DVD)
                {
                    colsocket.Visible = false;
                    colDungluong.Visible = false;
                    colbus.Visible = false;
                }
                else if (value == LinhKienType.Orther)
                {
                }
            }
        }

        public TBL_THIETBI ThietBi
        {
            get { return _thietbi; }
            set
            {
                _thietbi = value;
                if (value != null) Nap(value.ID);
            }
        }

        public event EventHandler Saving;


        private void OnSaving(EventArgs e)
        {
            EventHandler _handler = Saving;
            if (_handler != null) _handler(this, e);
        }

        private void gbList_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            int rowIndex = e.RowHandle;
            if (rowIndex >= 0)
            {
                rowIndex++;
                e.Info.DisplayText = rowIndex.ToString();
            }
        }

        private void gbList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                GridHitInfo no = gbList.CalcHitInfo(e.Location);
                if (no.InRow | no.InRowCell | no.HitTest == GridHitTest.EmptyRow)
                {
                    bm.SetPopupContextMenu(gcList, pm);
                }
                else
                {
                    bm.SetPopupContextMenu(gcList, null);
                }
            }
        }


        public void Nap()
        {
            Nap(ThietBi.ID);
        }

        public void Nap(int id)
        {
            try
            {
                if (!SqlHelperSmart.Check(DbHelper.ConnectionString)) return;

                tBL_LinhkienTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_LinhkienTableAdapter.FillBy(dsLinhKien.TBL_Linhkien, id, (short) Style);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý thiết bị");
                //throw;
            }
        }

        private void iCopy_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void iSelectAll_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void iDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void Deleted()
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iComponents))
            {
                return;
            }

            if (ShowQuestion("Bạn có chắc chắn muốn xóa không?", "Quản lý linh kiện") == DialogResult.No) return;

            if (gbList.SelectedRowsCount > 0)
            {
                gbList.DeleteSelectedRows();
            }
            else
            {
                gbList.DeleteRow(gbList.FocusedRowHandle);
            }

            gbList_RowUpdated(null, null);
        }

        private void iClear_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void iNap_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void iClose_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private void iSave_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        private bool Check()
        {
            dsLinhKien.TBL_LinhkienDataTable dt = dsLinhKien.TBL_Linhkien;
            for (int i = 0; i < dt.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                if (dr.RowState == DataRowState.Added)
                {
                    dr[dt.idloaiLKColumn] = _style;
                    dr[dt.idthietbiColumn] = ThietBi.ID;
                }
                else if (dr.RowState != DataRowState.Deleted)
                {
                    if (dr[dt.idnhasxColumn] == DBNull.Value)
                    {
                        MyBox.ShowWarning("Vui lòng chọn nhà sản xuất", "Thông báo");
                        dr.RowError = "Vui lòng chọn nhà sản xuất";
                        return false;
                    }
                }
            }
            return true;
        }

        public int Save()
        {
            if (!Check()) return 0;

            try
            {
                tBL_LinhkienTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_LinhkienTableAdapter.Adapter.RowUpdating += Adapter_RowUpdating;
                tBL_LinhkienTableAdapter.Adapter.RowUpdated += Adapter_RowUpdated;
                int row = tBL_LinhkienTableAdapter.Update(dsLinhKien.TBL_Linhkien);
                dsLinhKien.TBL_Linhkien.AcceptChanges();
                return row;
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý thiết bị");
            }
            return 0;
        }

        private void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Status == UpdateStatus.ErrorsOccurred)
            {
                ShowWarning(e.Errors.Message, "Quản lý linh kiện");
            }
        }

        private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {
            if (e.Row.RowState == DataRowState.Modified)
            {
                if (!TBL_quyenBL.isThaydoi(EnumComponent.iComponents))
                {
                    e.Status = UpdateStatus.SkipCurrentRow;
                    return;
                }
            }
        }

        private void gbList_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gbList.ClearColumnErrors();

            // gbList.UpdateCurrentRow();
            if (m_Column == Column.Lock) return;
            if (m_Column == Column.None)
            {
                if (e.Column.FieldName.Equals("idnhasx"))
                {
                    m_Column = Column.MaTB;
                }
            }

            switch (m_Column)
            {
                case Column.None:
                    return;
                case Column.MaTB:
                    m_Column = Column.Lock;
                    int row = gbList.GetDataSourceRowIndex(e.RowHandle);
                    {
                        dsLinhKien.TBL_LinhkienDataTable dt = dsLinhKien.TBL_Linhkien;
                        if (row >= dt.Count)
                        {
                            gbList.SetRowCellValue(e.RowHandle, coltinhtrang, 0);
                            gbList.SetRowCellValue(e.RowHandle, colidnoiBH, ThietBi.DChiBH);
                            gbList.SetRowCellValue(e.RowHandle, coltgianBH, ThietBi.TgianBH);
                            //gbList.SetRowCellValue(e.RowHandle, colngaysd, ThietBi.NgaySuDung);
                            gbList.SetRowCellValue(e.RowHandle, colidthietbi, ThietBi.ID);
                            //gbList.SetRowCellValue(e.RowHandle, "idloaiLK",(short)Style);
                            //gbList.UpdateCurrentRow();
                        }
                        else
                        {
                            DataRow dr = dt.Rows[row];
                            if (dr.RowState == DataRowState.Added)
                            {
                                if (dr[dt.tinhtrangColumn] == DBNull.Value)
                                {
                                    dr[dt.tinhtrangColumn] = 0;
                                }
                                if (dr[dt.noiBHColumn] == DBNull.Value)
                                {
                                    dr[dt.noiBHColumn] = ThietBi.DChiBH;
                                }

                                if (dr[dt.tgianBHColumn] == DBNull.Value)
                                {
                                    dr[dt.tgianBHColumn] = ThietBi.TgianBH;
                                }

                                dr[dt.idthietbiColumn] = ThietBi.ID;
                            }
                        }
                    }

                    m_Column = Column.None;
                    return;
            }
        }

        private void gbList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                Deleted();
            }
            ProcessDialogKey(e.KeyCode);
        }

        private void gbList_RowUpdated(object sender, RowObjectEventArgs e)
        {
            if (Save() == 0) return;
            Nap();
            NotSave = false;
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                    //case Keys.Alt | Keys.D:
                    //    //MessageBox.Show("You are stupid");
                    //    return true;

                    //// some more cases...  

                    //case Keys.F1:
                    //    //ucToolBar_HelpClick(ucBar);
                    //    F11Execute();
                    //    return true;
                    //case Keys.F3:
                    //    F3Execute();
                    //    return true;
                    //case Keys.F4:
                    //    F4Execute();
                    //    return true;
                    //case Keys.F5:
                    //    F5Execute();
                    //    return true;
                    //case Keys.F6:
                    //    F9Execute();
                    //    return true;
                    //case Keys.F7:
                    //    F7Execute();
                    //    return true;
                    //case Keys.F8:
                    //    F8Execute();
                    //    return true;
                    //case Keys.F9:
                    //    F9Execute();
                    //    return true;
                    //case Keys.F11:
                    //    F11Execute();
                    //    return true;
                    //case Keys.F12:
                    //    F12Execute();
                    //    return true;

                case Keys.Escape:
                    if (ParentForm != null) ParentForm.Close();
                    EscapeExecute();
                    return true;

                case Keys.Alt | Keys.X:
                    if (ParentForm != null) ParentForm.Close();
                    return true;

                case Keys.F10:
                    F10Execute();
                    if (ParentForm != null) ParentForm.Close();
                    return true;
            }

            return false;
        }

        private void F10Execute()
        {
        }

        private void EscapeExecute()
        {
        }

        private void gbList_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            NotSave = true;
        }
    }
}